package com.example.demo.util.filter;

import com.github.mgunlogson.cuckoofilter4j.CuckooFilter;
import com.google.common.base.Charsets;
import com.google.common.hash.Funnel;
import com.google.common.hash.Funnels;
import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * @author: Bin.L
 * @date: 2022/6/21  14:23
 * @description: 布谷过滤器 <href>https://github.com/MGunlogson/CuckooFilter4J</href>
 * 对比BloomFilter提供动态添加和删除项目的灵活性
 */
public class CuckooFilterExam {

    public static void main(String[] args) {

        CuckooFilterExam cuckooFilterExam = new CuckooFilterExam();
        cuckooFilterExam.intCuckooFilter();
        cuckooFilterExam.studentCuckooFilter();
    }

    public void intCuckooFilter() {
        // 创建一个整形CuckooFilter
        CuckooFilter<Integer> filter = new CuckooFilter.Builder<>(Funnels.integerFunnel(), 2000).build();

        filter.put(1);
        filter.put(2);
        filter.put(2);
        filter.put(3);
        filter.put(4);

        System.out.println("2  Does it exist? " + filter.mightContain(2));
        System.out.println("filter has item  " + filter.getCount());
        System.out.println("2  has count " + filter.approximateCount(2));
        // 获取负载因子
        System.out.println("Filter is " + String.format("%.0f%%", filter.getLoadFactor() * 100) + " loaded");
        System.out.println("delete 2 " + filter.delete(2));
    }

    public void studentCuckooFilter() {
        // 创建一个自定义对象CuckooFilter
        CuckooFilter<Student> studentFilter = new CuckooFilter.Builder<>((Funnel<Student>) (student, primitiveSink) -> primitiveSink.putString(student.toString(), Charsets.UTF_8), 200).build();

        Student zs = new Student("ZS",12);
        Student ls = new Student("LS",19);
        studentFilter.put(zs);
        studentFilter.put(ls);

        System.out.println(studentFilter.mightContain(zs));
    }

    @Data
    @AllArgsConstructor
    static class Student {
        private String name;
        private Integer age;

    }

}
